package com.hursing.tractor.controller;

import java.util.Collections;
import java.util.LinkedList;

import android.os.Handler;
import android.os.Message;

import com.hursing.tractor.baseview.UIView;
import com.hursing.tractor.model.Player;
import com.hursing.tractor.model.Card;
import com.hursing.tractor.model.GameData;
import com.hursing.tractor.model.Strategy;

final class DealStage extends Stage implements DealController {

	private static final int DEAL_INTERVAL = 80;
	private static final int KITTY_INTERVAL = 1500;
	private static final int MESSAGE_DEAL_ONE_CARD = 0;
	private static final int MESSAGE_START_BURIER = 1;
	
	private LinkedList<Card> mDealingCards = new LinkedList<Card>();
	private int mDealedCount;
	private boolean mIsPause;
	
	private Handler mDealHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_DEAL_ONE_CARD:
				notifyDrawOneCard();
				break;
			case MESSAGE_START_BURIER:
				UIView.sViews[UIView.VIEW_FLIP_PANEL].visible(false);
				nextStage();
				break;
			default:
				break;
			}
		}
	};
	
	@Override
	void start() {
		GameData.instance().kittyCards().clear();
		GameData.instance().flip(null, null).
			score(0).
			clearPlayedCards();
		
		for (int i = 0; i < Player.PLAYER_COUNT; i++) {
			GameData.instance().player(i).getReadyForNewGame();
		}
		
		UIView.sViews[UIView.VIEW_KITTY_CARD].visible(false);
		UIView.sViews[UIView.VIEW_FLIP_PANEL].visible(true);
		
		mDealedCount = 0;
		Card.getAllCards(mDealingCards);
		Collections.shuffle(mDealingCards);
		Card.calculateCardOrder();
		int kittyCount = Strategy.instance().getKittyCount();
		while (kittyCount-- > 0) {
			GameData.instance().kittyCards().add(mDealingCards.removeLast());
		}
		recover();
	}
	
	@Override
	public void pause() {
		mDealHandler.removeCallbacksAndMessages(null);
		mIsPause = true;
		UIView.sViews[UIView.VIEW_PAUSE_BUTTON].visible(!mIsPause);
		UIView.sViews[UIView.VIEW_CONTINUE_BUTTON].visible(mIsPause);
	}
	
	@Override
	void recover() {
		nextDealStep();
		mIsPause = false;
		UIView.sViews[UIView.VIEW_PAUSE_BUTTON].visible(!mIsPause);
		UIView.sViews[UIView.VIEW_CONTINUE_BUTTON].visible(mIsPause);
	}
	
	boolean isPause() {
		return mIsPause;
	}
	
	private void nextDealStep() {
		if (mDealingCards.size() != 0) {
			mDealHandler.sendEmptyMessageDelayed(MESSAGE_DEAL_ONE_CARD, DEAL_INTERVAL);
		} else {
			mDealHandler.sendEmptyMessageDelayed(MESSAGE_START_BURIER, KITTY_INTERVAL);
		}
	}
	
	/**
	 * 通知拿牌
	 */
	private void notifyDrawOneCard() {
		int dealToPosition = (GameData.instance().housePosition() + mDealedCount) % Player.PLAYER_COUNT;
		GameData.instance().player(dealToPosition).drawOneCard(this);
	}
	
	/**
	 * 玩家拿一张牌
	 * @return
	 */
	@Override
	public Card dealOneCard() {
		Card card = mDealingCards.removeFirst();
		mDealedCount++;
		UIView.sViews[UIView.VIEW_CURRENT_REMAINING_LABEL].text(String.valueOf(mDealingCards.size()));
		nextDealStep();
		return card;
	}

}
